package com.b.controller;

import com.b.domain.Category;
import com.b.service.CategoryService;
import com.b.vo.Result;
import jakarta.annotation.Resource;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.SearchPage;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 分区表(category)表控制层
 *
 * @author xxxxx
 */
@RestController
@RequestMapping("/category")
public class CategoryController {
    /**
     * 服务对象
     */
    @Resource
    private CategoryService categoryService;
    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("selectOne")
    public Category selectOne(Integer id) {
        return categoryService.selectByPrimaryKey(id);
    }
    @GetMapping("getAll")
    public List<Category> getAll() {
        return categoryService.getAll();
    }
    @GetMapping("list")
    public SearchPage<Category> list(@RequestParam(value = "pageNum", defaultValue = "1") Integer page,
                                     @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                     @RequestParam(value = "type", defaultValue = "") String type)
    {
        PageRequest pageRequest = PageRequest.of(page - 1, pageSize);

        return categoryService.list( type, pageRequest);
    }
    //增改
    @RequestMapping("save")
    public Result save(Category category) {
        try {
            if (category.getId() == null) {
                boolean b = categoryService.add(category);
                return b ? new Result().setCode("200").setMsg("添加成功") : new Result().setCode("400").setMsg("添加失败");
            } else {
                boolean f = categoryService.update(category);
                return f ? new Result().setCode("200").setMsg("修改成功") : new Result().setCode("400").setMsg("修改失败");
            }
        } catch (Exception e) {
            return new Result().setCode("500").setMsg("服务器异常：" + e.getMessage());
        }
    }
    @PostMapping("delete/{id}")
    public Result delete(@PathVariable ("id") Integer id){
        try {
            boolean b = categoryService.deleteByPrimaryKey(id);
            if (b) {
                return new Result().setCode("200").setMsg("删除成功");
            } else {
                return new Result().setCode("400").setMsg("删除失败");
            }
        } catch (Exception e) {
            return new Result().setCode("500").setMsg("服务器异常：" + e.getMessage());
        }
    }


}
